<template>
  <el-select v-model="sval" 
         :clearable="clearable" 
          filterable 
          placeholder="请选择作物" 
          :style="{width}" 
          @focus="onFocus"
          @change="onChcange">
    <el-option v-for="dt in lists" :key="dt.code" :value="dt.code" :label="dt.meaning" />
  </el-select>
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { getCropList } from '@/api/plant'

const props = defineProps({
  modelValue: '',
  width: {
    type: String,
    default: '100%'
  },
  code: {
    type: String,
    default: 'TANC_CROP'
  },
  param1:{
    type: String,
    default: ''
  },
  param2: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: true
  },
  keyName: '' // 返回的属性名对应的值
})
const emit = defineEmits(['update:modelValue','init','change','changeName','focus'])
const sval = ref('')
const lists = ref('')

onMounted(() => {
  getTableData()
})

watch(() => props.modelValue, (n, o) => {
  sval.value = n
})
watch(() => props.param2, (n, o) => {
  getTableData()
})

watch(() => props.param1, (n, o) => {
  getTableData()
})

const getTableData = async() => {
  const res = await getCropList({ page: 1, limit: 100, lovCode: props.code,param1: props.param1, param2: props.param2 })
  if (res.code === 0) {
    lists.value = res.data
    sval.value = props.modelValue || '' // 设置默认选项
    if(lists.value.length>0){
      emit('init', lists.value[0])
    }else{
      emit('init', false)
    }
  }
}

const onChcange = () => {
  if (props.keyName) {
    const item = lists.value.find(ele => ele.id === sval.value)
    emit('update:modelValue', item[props.keyName])
    emit('change', sval.value)
  } else {
    if (sval.value) {
      const item = lists.value.find((ele) => {
        return ele.code === sval.value
      })
      emit('update:modelValue', sval.value)
      emit('change',item)
      emit('changeName', item.meaning)
    } else {
      emit('update:modelValue', '')
      emit('change', '')
      emit('changeName', '')
    }
  }
}

const onFocus = () => {
    emit('focus', {})
}
</script>

<style scoped lang="scss">
</style>
